<template>
  <view class="question-page">
    <!-- #ifdef APP -->
    <u-navbar title="补全资料" :autoBack="true" :placeholder="true">></u-navbar>
    <!-- #endif -->
    <view class="contentBox">
      <view class="page-title">补全资料</view>
      <view class="content-box">
        <view class="title">
          <image src="../../static/user/icon_tx.png" class="icon"></image>
          头像
        </view>
        <view class="avatar-box">
          <view class="default-avatar" v-for="(item, index) in defaultAvatar" :key="index" @click="avatarIndex = index">
            <view class="label" v-if="avatarIndex == index">默认</view>
            <image src="../../static/common/icon_xuan1.png" class="select" v-if="avatarIndex == index"></image>
            <image src="../../static/common/icon_xuan.png" class="select" v-else></image>
            <u-image :src="item.allurl" class="avatar" width="100%" height="100%" loadingIcon="" :lazy-load="true" mode="aspectFill"></u-image>
          </view>
          <view class="default-avatar">
            <uploadImage
              @uploadSuccess="uploadSuccess"
              name="image"
              :maxCount="1"
              width="192rpx"
              height="192rpx">
			</uploadImage>
          </view>
        </view>
      </view>

      <view class="content-box">
        <view class="title">
          <image src="../../static/user/icon_nc.png" class="icon"></image>
          昵称
        </view>
        <view class="input-box">
          <u-input
            v-model="userInfo.nickname"
            placeholder="请输入昵称"
            :clearable="true"
            border="none"
            :customStyle="{ height: '88rpx' }"></u-input>
          <view class="random" @click="getRandomName">
            <image src="../../static/user/icon_sj.png" class="image"></image>
            随机
          </view>
        </view>
      </view>
      <view class="content-group">
        <view class="content-box">
          <view class="title">
            <image src="../../static/user/icon_nl.png" class="icon"></image>
            年龄
          </view>
          <view class="input-box">
            <u-input
              v-model="userInfo.age"
              placeholder="请输入年龄"
              type="number"
              :clearable="true"
              border="none"
              :customStyle="{ height: '88rpx' }"></u-input>
          </view>
        </view>
        <view style="width: 20rpx"></view>
        <view class="content-box">
          <view class="title">
            <image src="../../static/user/icon_cs.png" class="icon"></image>
            常驻城市
          </view>
          <view class="input-box city" @click="showArea = true">
			<text v-if="userInfo.city">{{userInfo.city}} </text>
			<text v-else style="color: #afafaf;">请选择城市</text>
          </view>
        </view>
      </view>
      <view class="content-box">
        <view class="title">
          <image src="../../static/user/icon_yqm.png" class="icon"></image>
          邀请码（必填）
        </view>
        <view class="input-box">
          <u-input
            v-model="userInfo.parent_user_id"
            placeholder="请输入邀请码"
            :clearable="true"
            border="none"
            :customStyle="{ height: '88rpx' }">
			</u-input>
        </view>
      </view>
      <view class="button-group">
        <view class="button1" @click="$u.throttle(updateUserInfo, 2000)">
          提交
        </view>
      </view>
    </view>
    <u-picker
      :show="showArea"
      ref="uPicker"
      cancelText=""
      :defaultIndex="areaIndex"
      :columns="columns"
      @confirm="confirmArea"
      @close="showArea = false"
      :closeOnClickOverlay="true"
      @change="changeHandler">
	</u-picker>
    <view style="height: 20rpx"></view>
  </view>
</template>

<script>
import { HTTP_REDIRECT_URL } from "@/config/app";
import uploadImage from "@/components/UploadImage.vue";
export default {
  data() {
    return {
      gender: 1, //性别 1男 2女
      avatarIndex: 0,
      userInfo: {
        avatar: "",
        nickname: "",
        city: "",
        age: "",
        parent_user_id: "",
      },
      showArea: false,
      areaIndex: [0, 0],
      columns: [[], []],
      columnData: [[], []],
      defaultAvatar: [],
    };
  },
  components: {
    uploadImage: uploadImage,
  },
  onLoad(options) {
    this.getUserInfo();
    this.getLocation();
  },
  onShow() {
    let parent_user_id = uni.getStorageSync("parent_user_id");
    if (parent_user_id) {
      this.userInfo.parent_user_id = parent_user_id;
    }
    this.getLocation();
  },
  methods: {
    getUserInfo() {
      this.$Api["user"].getUserInfo().then((res) => {
        this.gender = res.data.gender;
        if (this.gender == 1 && this.userInfo.age == "") {
          this.userInfo.age = 30;
        }
        this.userInfo.parent_user_id = res.data.parent_user_id;
        this.getDefaultAvatar();
        this.getRandomName();
      });

      // this.$Api.common
      //    .getParentMobile({
      //      mobile: username,
      //    })
      //    .then((res1) => {
      // 	this.userInfo.parent_user_id=res1.data.parent_user_id
      // 	})
    },
    //通过经纬度获取城市名称
    getLocation() {
      uni.getLocation({
        type: "wgs84",
        altitude: true,
        geocode: true,
        success: (e) => {
          uni.setStorageSync("latitude", e.latitude);
          uni.setStorageSync("longitude", e.longitude);
          console.log(e, "horizontalAccuracy");
          this.$Api["user"]
            .getOnly({
              only_value: e.longitude + e.latitude,
            })
            .then((res1) => {
              console.log(res1, "res1");
              // this.userInfo.parent_user_id = res1.data;
            });
          this.$Api.common
            .getCityByLat({
              lng: e.longitude.toString(),
              lat: e.latitude.toString(),
            })
            .then((res) => {
              console.log(res, "resresresresres");
              this.userInfo.city = res.data.name;
              this.getAreaTree();
            });
        },
        fail: (err) => {
          reject(new Error(`获取位置失败: ${err.errMsg || "未知错误"}`));
        },
      });
    },
    //获取城市信息，并赋值默认值
    getAreaTree() {
      this.$Api["common"].getAreaTree().then((res) => {
        this.columnData = this.extractChildNames(res.data);
        console.log(this.columnData, "columnData========columnData");
        let areaIndex = this.findCityIndex(this.userInfo.city, this.columnData);
        if (
          Array.isArray(res.data) &&
          res.data.length > 0 &&
          Array.isArray(res.data[0].childlist)
        ) {
          const columns = [
            res.data.map((item) => item.name),
            res.data[areaIndex[0]].childlist.map((item) => item.name),
          ];
          this.columns = [...columns];
        } else {
          console.error("Invalid data structure");
          // 或者根据需要设置默认值给 this.columns
          this.columns = [[], []];
        }
        this.areaIndex = areaIndex;
      });
    },
    //根据城市名称查询索引
    findCityIndex(cityName, cities) {
      for (let i = 0; i < cities.length; i++) {
        let row = cities[i];
        for (let j = 0; j < row.length; j++) {
          if (row[j] === cityName) {
            return [i, j]; // 返回行和列的索引
          }
        }
      }
      return null; // 如果没有找到市区，返回null
    },
    //格式化城市信息
    extractChildNames(data) {
      return data.map((item) => {
        // 如果 childlist 存在且不为空，则提取所有城市的 name 属性
        if (item.childlist && item.childlist.length > 0) {
          return item.childlist.map((child) => child.name);
        } else {
          // 否则返回一个空数组
          return [];
        }
      });
    },
    //修改选择的城市
    changeHandler(e) {
      const {
        columnIndex,
        value,
        values, // values为当前变化列的数组内容
        index,
        picker = this.$refs.uPicker,
      } = e;
      // 当第一列值发生变化时，变化第二列(后一列)对应的选项
      if (columnIndex === 0) {
        // picker为选择器this实例，变化第二列对应的选项
        picker.setColumnValues(1, this.columnData[index]);
      }
    },
    //确认选择的城市
    confirmArea(e) {
      this.userInfo.city = e.value[1];
      this.showArea = false;
    },
    //获取默认头像列表
    getDefaultAvatar() {
      this.$Api["common"]
        .getUserConfig({
          site: "headimg",
          gender: this.gender,
        })
        .then((res) => {
          this.defaultAvatar = res.data;
        });
    },
    //获取随机昵称
    getRandomName() {
      this.$Api["common"]
        .getUserConfig({
          site: "rand_nickname",
          gender: this.gender,
        })
        .then((res) => {
          this.userInfo.nickname = res.data;
        });
    },
    //修改用户信息
    updateUserInfo() {
      if (this.avatarIndex != null) {
        this.userInfo.avatar = this.defaultAvatar[this.avatarIndex].url;
      }
      if (this.userInfo.avatar == "") {
        return this.$Toast("请选择或上传头像");
      }
      if (this.userInfo.nickname == "") {
        return this.$Toast("请输入昵称");
      }
      if (this.userInfo.age == "") {
        return this.$Toast("请输入年龄");
      }
      if (this.userInfo.age < 18 || this.userInfo.age > 100) {
        return this.$Toast("年龄需要大于18岁小于100岁");
      }
      if (this.userInfo.city == "") {
        return this.$Toast("请选择常驻城市");
      }
      if (!this.userInfo.parent_user_id && this.gender == 1) {
        return this.$Toast("请输入邀请码");
      }
      let browser_type;
      uni.getSystemInfo({
        success: function (res) {
          browser_type = res.version;
        },
      });
      this.$Api["user"].updateUserInfo(this.userInfo).then((res) => {
        uni.removeStorageSync("parent_user_id");
        // 匹配en中是否含有MicroMessenger字符串
        if (browser_type == "") {
          uni.showModal({
            content: "请下载app进行使用",
            showCancel: false,
            confirmText: "确定",
            success: function (res) {
              console.log(res, "res");
              if (res.confirm) {
                uni.navigateTo({
                  url: "/pages/download/download",
                });
                // let browser = window.navigator.userAgent.toLowerCase()
                // // 匹配en中是否含有MicroMessenger字符串
                // if (browser.match(/MicroMessenger/i) != 'micromessenger') {
                // 	uni.reLaunch({
                // 		url: '/pages/download/download'
                // 	});
                // }else{
                // 	uni.reLaunch({
                // 		url: '/pages/download/download'
                // 	});
                // }
                // } else if (res.cancel) {
                // 	let browser = window.navigator.userAgent.toLowerCase()
                // 	// 匹配en中是否含有MicroMessenger字符串
                // 	if (browser.match(/MicroMessenger/i) != 'micromessenger') {
                // 		uni.reLaunch({
                // 			url: '/pages/download/download'
                // 		});
                // 	}else{
                // 		uni.reLaunch({
                // 			url: '/pages/download/download'
                // 		});
                // 	}
              }
            },
          });
        } else {
          uni.switchTab({
            url: "/pages/index/index",
          });
        }
      });
    },
    uploadSuccess(e) {
      if (e.fileList == "") {
        this.avatarIndex = 0;
        this.userInfo.avatar = "";
      } else {
        this.userInfo.avatar = e.fileList;
        this.avatarIndex = null;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.question-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f7f8fa;
  position: relative;

  .contentBox {
    min-height: 80vh;
    margin: 20rpx;
    padding: 38rpx 40rpx 38rpx;
    box-shadow: 0rpx 4rpx 32rpx 0rpx #fff0fd;
    border-radius: 32rpx;
    background: linear-gradient(180deg, #ffdaf5 0%, #ffffff 5%);

    .page-title {
      font-weight: bold;
      font-size: 44rpx;
      color: #323334;
    }

    .content-group {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .content-box,
    .image-box {
      margin-top: 40rpx;
      flex: 1;

      .avatar-box {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-auto-flow: row;
        grid-gap: 20rpx;

        .default-avatar {
          width: 192rpx;
          height: 192rpx;
          position: relative;
          border-radius: 16rpx;
          overflow: hidden;

          .label {
            position: absolute;
            left: 0;
            top: 0;
            z-index: 1;
            width: 76rpx;
            height: 28rpx;
            font-size: 20rpx;
            color: #ffffff;
            text-align: center;
            background: #f169f6;
            border-radius: 16rpx 0rpx 16rpx 0rpx;
          }

          .select {
            position: absolute;
            right: 0;
            top: 0;
            z-index: 1;
            width: 32rpx;
            height: 32rpx;
          }

          .avatar {
            width: 100%;
            height: 100%;
          }
        }
      }

      .title {
        display: flex;
        align-items: center;
        font-size: 28rpx;
        margin: 42rpx 0 20rpx;

        .icon {
          width: 28rpx;
          height: 28rpx;
          margin-right: 8rpx;
        }
      }

      .input-box {
        height: 88rpx;
        line-height: 88rpx;
        background: #f6f6f6;
        border-radius: 16rpx;
        flex: 1;
        display: flex;
        align-items: center;
        padding: 0 20rpx;

        .random {
          display: flex;
          align-items: center;
          font-size: 28rpx;
          color: #f16af6;
          margin: 0 28rpx;

          .image {
            width: 36rpx;
            height: 36rpx;
            margin-right: 8rpx;
          }
        }
      }
    }

    .button-group {
      .button1 {
        margin: 160rpx auto 0;
        width: 628rpx;
        height: 88rpx;
        font-weight: bold;
        font-size: 30rpx;
        color: #ffffff;
        text-align: center;
        line-height: 88rpx;
        background: linear-gradient(135deg, #fe93bf 0%, #a27aff 100%);
        box-shadow: 0rpx 4rpx 10rpx 0rpx #fdc4ff;
        border-radius: 44rpx;
      }
    }
  }
}
</style>
